package com.li.away3d.terrain
{
import away3d.materials.MaterialBase;
import away3d.primitives.Plane;

import flash.display.BitmapData;

public class PerlinTerrain extends Plane
{
    public function PerlinTerrain(material:MaterialBase = null, width:Number = 100, height:Number = 100, segmentsW:uint = 1, segmentsH:uint = 1, yUp:Boolean = true)
    {
        super(material, width, height, segmentsW, segmentsH, yUp);
    }

    public function generate(image:BitmapData, height:Number, debug:Boolean = false):void
    {
        var i:uint, j:uint, imgx:uint, imgy:uint, vertexIndex:uint;
        var vertices:Vector.<Number> = geometry.subGeometries[0].vertexData;
        var gray:Number;
        var imgdw:Number = image.width/segmentsW;
        var imgdh:Number = image.height/segmentsH;
        image.lock();
        for(j = 0; j <= segmentsH; j++)
        {
            for(i = 0; i <= segmentsW; i++)
            {
                imgx = i*imgdw;
                imgy = j*imgdh;
                gray = (image.getPixel(imgx, imgy) & 0x0000FF)/255;
                if(debug) image.setPixel(imgx, imgy, 0xFF0000);
                vertexIndex = 3*(j*segmentsW + i);
                trace(vertexIndex + "/" + vertices.length);
                vertices[vertexIndex + 1] += height*gray;
            }
        }
        image.unlock();
        geometry.subGeometries[0].updateVertexData(vertices);
    }
}
}
